

function renameFieldName( field, stringVal )
{
    if( field !== 'undefined')
    {
        var stringName      = field.attr('name');
        var explodeName     = stringName.split('[');
        field.attr('name', 'fields[' + stringVal + '][' + explodeName[2]);
    }
}

function initializeElements()
{
    // spinners
    $('.spinner').btSpinner({
        step: 1,
        orientation: 'vertical',
        position: 'right'
    });
    
    // toggle switch
    $('.switch').bootstrapSwitch();
    
    // auto-complete plural form
    $('#name').change(function() {
       $('#plural-name').val( plural($(this).val()) );
    });
    
    // default values
    $('.data-type').find('option').hide();
    $('.data-type').find('option.text').show();
    $('.max-length').val('100');
    
    // primary key values
    $('.max-length:first').val('10');
    $('.data-type:first').find('option.number').show();
    $('.data-type:first').val('int');
}

function addEventListeners()
{
    $('.input-type').off();
    $('.field-name').off();
    $('button.remove').off();
    $('button.add').off();
    $('button.refresh').off();

    // field-name
    $('.field-name').change(function(e) {
        e.preventDefault();
        
        var parent      = $(this).closest('tr');
        var stringVal   = $(this).val().toString().toDash();

        renameFieldName( parent.find('.input-type'), stringVal );
        renameFieldName( parent.find('.field-name'), stringVal );
        renameFieldName( parent.find('.data-type'), stringVal );
        renameFieldName( parent.find('.default-value'), stringVal );
        renameFieldName( parent.find('.min-length'), stringVal );
        renameFieldName( parent.find('.max-length'), stringVal );
        renameFieldName( parent.find('.required'), stringVal );
        renameFieldName( parent.find('.other-option'), stringVal );
        
    });

    // remove
    $('button.remove').click(function(e) {
        e.preventDefault();
        $(this).closest('tr').remove();
    });

    // add
    $('button.add').click(function(e) {
        e.preventDefault();
        var input = $(this).closest('tr');

        var markup = '';
        markup = '<tr>\n\
                    <td>\n\
                        <span class="input-group-btn">\n\
                            <button type="button" class="btn btn-default remove"><i class="fa fa-minus"></i></button>\n\
                            <button type="button" class="btn btn-default add"><i class="fa fa-plus"></i></button>\n\
                        </span>\n\
                    </td>\n\
                    <td>\n\
                        <select name="fields[first-name][type]" class="input-type form-control">\n\
                            <optgroup label="Text Inputs">\n\
                                <option value="text" selected="selected"> Text Input </option>\n\
                                <option value="email"> Email Input </option>\n\
                                <option value="url"> URL Input </option>\n\
                                <option value="password"> Password Input </option>\n\
                                <option value="textarea"> Text Area </option>\n\
                            </optgroup>\n\
                            <optgroup label="Advanced Text Inputs">\n\
                                <option value="cle"> CLE WYSIWYG </option>\n\
                                <option value="cke"> CKE WYSIWYG </option>\n\
                            </optgroup>\n\
                            </optgroup>\n\
                            <optgroup label="Number Inputs">\n\
                                <option value="number"> Number </option>\n\
                                <option value="spinner"> Spinner </option>\n\
                            </optgroup>\n\
                            <optgroup label="Date Inputs">\n\
                                <option value="time"> Time Picker </option>\n\
                                <option value="date"> Date Picker </option>\n\
                                <option value="date-range"> Date Range Picker </option>\n\
                                <option value="datetime"> Datetime Picker </option>\n\
                                <option value="datetime-range"> Datetime Range Picker </option>\n\
                                <option value="timezone"> Timezone </option>\n\
                            </optgroup>\n\
                            <optgroup label="Data Inputs">\n\
                                <option value="dropdown"> Dropdown </option>\n\
                                <option value="multi-dropdown"> Multi Dropdown </option>\n\
                                <option value="radio"> Radio Button </option>\n\
                                <option value="checkbox"> Checkbox </option>\n\
                                <option value="tagsinput"> Tagsinput </option>\n\
                            </optgroup>\n\
                            <optgroup label="File Inputs">\n\
                                <option value="image-upload"> Image Upload </option>\n\
                                <option value="button-upload"> Button Upload </option>\n\
                                <option value="file-upload"> File Upload </option>\n\
                            </optgroup>\n\
                            <optgroup label="Advanced Inputs">\n\
                                <option value="toggle"> Toggle </option>\n\
                                <option value="color"> Color Picker </option>\n\
                                <option value="masked"> Masked Input </option>\n\
                                <option value="captcha"> Captcha </option>\n\
                                <option value="geolocation"> Geolocation </option>\n\
                            </optgroup>\n\
                        </select>\n\
                    </td>\n\
                    <td>\n\
                        <input type="text" name="fields[first-name][field-name]" class="field-name form-control" placeholder="first_name">\n\
                    </td>\n\
                    <td>\n\
                        <select name="fields[first-name][data-type]" class="data-type form-control">\n\
                            <option value="int" class="number">Int</option>\n\
                            <option value="bigint" class="number">Big Int</option>\n\
                            <option value="decimal" class="number">Decimal</option>\n\
                            <option value="float" class="number">Float</option>\n\
                            <option value="double" class="number">Double</option>\n\
                            <option value="real" class="number">Real</option>\n\
                            <option value="bit" class="number">Bit</option>\n\
                            <option value="bolean" class="number boolean">Boolean</option>\n\
                            <option value="serial" class="number">Serial</option>\n\
                            <option value="date" class="date">Date</option>\n\
                            <option value="datetime" class="date datetime">Datetime</option>\n\
                            <option value="timestamp" class="date datetime">Timestamp</option>\n\
                            <option value="time" class="time">Time</option>\n\
                            <option value="year" class="year">Year</option>\n\
                            <option value="char" class="text">Char</option>\n\
                            <option value="varchar" class="text" selected="selected">Varchar</option>\n\
                            <option value="tinytext" class="text">Tiny Text</option>\n\
                            <option value="text" class="text">Text</option>\n\
                            <option value="mediumtext" class="text">Medium Text</option>\n\
                            <option value="longtext" class="text">Long Text</option>\n\
                            <option value="enum" class="multi-dropdown">Enum</option>\n\
                            <option value="set" class="multi-dropdown">Set</option>\n\
                        </select>\n\
                    </td>\n\
                    <td>\n\
                        <input type="text" name="fields[first-name][default-value]" class="default-value form-control" placeholder="Default Value">\n\
                    </td>\n\
                    <td>\n\
                        <div class="input-group">\n\
                            <input type="text" name="fields[first-name][min-length]" class="min-length form-control spinner" placeholder="0">\n\
                        </div>\n\
                    </td>\n\
                    <td>\n\
                        <div class="input-group">\n\
                            <input type="text" name="fields[first-name][max-length]" class="max-length form-control spinner" placeholder="25" value="25">\n\
                        </div>\n\
                    </td>\n\
                    <td>\n\
                        <div class="input-group">\n\
                            <input type="checkbox" name="fields[first-name][required]" class="required form-control switch" data-on-text="yes" data-off-text="no" checked="checked">\n\
                        </div>\n\
                    </td>\n\
                    <td class="other-options">\n\
                        &nbsp;\n\
                    </td>\n\
                </tr>\n';

        input.after(markup);
        
        var newInput = input.next();
        
        // initialize elements of new row
        newInput.find('.switch').bootstrapSwitch();
        newInput.find('.spinner').btSpinner({
            step: 1,
            orientation: 'vertical',
            position: 'right'
        });
        
        // new row default values
        newInput.find('.data-type').find('option').hide();
        newInput.find('.data-type').find('option.text').show();
        newInput.find('.max-length').val('100');

        addEventListeners();
    });
    
    // refresh
    $('button.refresh').click(function(e) {
        e.preventDefault();
        var fields = '<tr>\n\
                        <td>\n\
                            <span class="input-group-btn">\n\
                                <button type="button" class="btn btn-default refresh"><i class="fa fa-refresh"></i></button>\n\
                                <button type="button" class="btn btn-default add"><i class="fa fa-plus"></i></button>\n\
                            </span>\n\
                        </td>\n\
                        <td>\n\
                            <select name="fields[id][type]" class="input-type form-control" readonly="readonly">\n\
                                <optgroup label="Text Inputs">\n\
                                    <option value="text"> Text Input </option>\n\
                                    <option value="email"> Email Input </option>\n\
                                    <option value="url"> URL Input </option>\n\
                                    <option value="password"> Password Input </option>\n\
                                    <option value="textarea"> Text Area </option>\n\
                                </optgroup>\n\
                                <optgroup label="Advanced Text Inputs">\n\
                                    <option value="cle"> CLE WYSIWYG </option>\n\
                                    <option value="cke"> CKE WYSIWYG </option>\n\
                                </optgroup>\n\
                                </optgroup>\n\
                                <optgroup label="Number Inputs">\n\
                                    <option value="number" selected="selected"> Number </option>\n\
                                    <option value="spinner"> Spinner </option>\n\
                                </optgroup>\n\
                                <optgroup label="Date Inputs">\n\
                                    <option value="time"> Time Picker </option>\n\
                                    <option value="date"> Date Picker </option>\n\
                                    <option value="date-range"> Date Range Picker </option>\n\
                                    <option value="datetime"> Datetime Picker </option>\n\
                                    <option value="datetime-range"> Datetime Range Picker </option>\n\
                                    <option value="timezone"> Timezone </option>\n\
                                </optgroup>\n\
                                <optgroup label="Data Inputs">\n\
                                    <option value="dropdown"> Dropdown </option>\n\
                                    <option value="multi-dropdown"> Multi Dropdown </option>\n\
                                    <option value="radio"> Radio Button </option>\n\
                                    <option value="checkbox"> Checkbox </option>\n\
                                    <option value="tagsinput"> Tagsinput </option>\n\
                                </optgroup>\n\
                                <optgroup label="File Inputs">\n\
                                    <option value="image-upload"> Image Upload </option>\n\
                                    <option value="button-upload"> Button Upload </option>\n\
                                    <option value="file-upload"> File Upload </option>\n\
                                </optgroup>\n\
                                <optgroup label="Advanced Inputs">\n\
                                    <option value="toggle"> Toggle </option>\n\
                                    <option value="color"> Color Picker </option>\n\
                                    <option value="masked"> Masked Input </option>\n\
                                    <option value="captcha"> Captcha </option>\n\
                                    <option value="geolocation"> Geolocation </option>\n\
                                </optgroup>\n\
                            </select>\n\
                        </td>\n\
                        <td>\n\
                            <input type="text" name="fields[id][field-name]" class="field-name form-control" placeholder="id" value="id">\n\
                        </td>\n\
                        <td>\n\
                            <select name="id[data-type]" class="data-type form-control" readonly="readonly">\n\
                                <option value="int" class="number">Int</option>\n\
                                <option value="int" class="number" selected="selected">Unsigned Int</option>\n\
                                <option value="bigint" class="number">Big Int</option>\n\
                                <option value="decimal" class="number">Decimal</option>\n\
                                <option value="float" class="number">Float</option>\n\
                                <option value="double" class="number">Double</option>\n\
                                <option value="real" class="number">Real</option>\n\
                                <option value="bit" class="number">Bit</option>\n\
                                <option value="bolean" class="number boolean">Boolean</option>\n\
                                <option value="serial" class="number">Serial</option>\n\
                                <option value="date" class="date">Date</option>\n\
                                <option value="datetime" class="date datetime">Datetime</option>\n\
                                <option value="timestamp" class="date datetime">Timestamp</option>\n\
                                <option value="time" class="time">Time</option>\n\
                                <option value="year" class="year">Year</option>\n\
                                <option value="char" class="text">Char</option>\n\
                                <option value="varchar" class="text" selected="selected">Varchar</option>\n\
                                <option value="tinytext" class="text">Tiny Text</option>\n\
                                <option value="text" class="text">Text</option>\n\
                                <option value="mediumtext" class="text">Medium Text</option>\n\
                                <option value="longtext" class="text">Long Text</option>\n\
                                <option value="enum" class="multi-dropdown">Enum</option>\n\
                                <option value="set" class="multi-dropdown">Set</option>\n\
                            </select>\n\
                        </td>\n\
                        <td>\n\
                            <input type="text" name="fields[id][default-value]" class="default-value form-control" placeholder="Default Value" readonly="readonly">\n\
                        </td>\n\
                        <td>\n\
                            <div class="input-group">\n\
                                <input type="text" name="fields[id][min-length]" class="min-length form-control spinner" placeholder="0" readonly="readonly">\n\
                            </div>\n\
                        </td>\n\
                        <td>\n\
                            <div class="input-group">\n\
                                <input type="text" name="fields[id][max-length]" class="max-length form-control spinner" placeholder="10" value="10" readonly="readonly">\n\
                            </div>\n\
                        </td>\n\
                        <td>\n\
                            <div class="input-group">\n\
                                <input type="checkbox" name="fields[id][required]" class="required form-control switch" data-on-text="yes" data-off-text="no" checked="checked" readonly="readonly">\n\
                            </div>\n\
                        </td>\n\
                        <td class="other-options">\n\
                            &nbsp;\n\
                        </td>\n\
                    </tr>\n';
        $('#fields-table tbody').html(fields);
        addEventListeners();
    });
    
    $('.input-type').change(function() {
       
        var inputType   = $(this).val();
        
        var parent          = $(this).closest('tr');
        var fieldName       = parent.find('.field-name');
        var dataType        = parent.find('.data-type');
        var defaultValue    = parent.find('.default-value');
        var minLength       = parent.find('.min-length');
        var maxLength       = parent.find('.max-length');
        var otherOption     = parent.find('.other-options');
        
        var defaultOtherOption  = '&nbsp;';
        var fieldNameVal        = fieldName.val().toString().toDash();
        
        // text input
        if( inputType === 'text') {
           fieldName.attr('placeholder', 'first_name');
           dataType.find('option').hide();
           dataType.find('option.text').show();
           dataType.val('varchar');
           maxLength.val('100');
           otherOption.html(defaultOtherOption);
        }
        
        // email input
        if( inputType === 'email') {
           fieldName.attr('placeholder', 'email');
           dataType.find('option').hide();
           dataType.find('option.text').show();
           dataType.val('varchar');
           maxLength.val('100');
           otherOption.html(defaultOtherOption);
        }
        
        // url input
        if( inputType === 'url') {
           fieldName.attr('placeholder', 'url');
           dataType.find('option').hide();
           dataType.find('option.text').show();
           dataType.val('text');
           maxLength.val('1000');
           otherOption.html(defaultOtherOption);
        }
        
        // password input
        if( inputType === 'password') {
           fieldName.attr('placeholder', 'password');
           dataType.find('option').hide();
           dataType.find('option.text').show();
           maxLength.val('100');
           
           var confirmPassword = 'confirm password <input type="checkbox" name="fields[' +fieldNameVal+ '][confirm-password]" class="other-option form-control switch" data-on-text="yes" data-off-text="no" value="yes" checked="checked">';
           otherOption.html(confirmPassword);
           otherOption.find('.switch').bootstrapSwitch();
        }
        
        // long text, wysiwyg editors
        if( inputType === 'textarea' || inputType === 'wysiwyg' || inputType === 'cle' || inputType === 'cke') {
            fieldName.attr('placeholder', 'description');
            dataType.find('option').hide();
            dataType.find('option.text').show();
            dataType.val('text');
            maxLength.val('1000');
            
            var wysiwygDropdown = '<select name="fields[' +fieldNameVal+ '][wysiwyg]" class="other-option form-control">\n\
                <option value="none"> - None - </option>\n\
                <option value="cle">CLE Editor</option>\n\
                <option value="cke">CKE Editor</option>\n\
            </select>\n';
            otherOption.html(wysiwygDropdown);
        }
        
        // number
        if( inputType === 'number' ) {
           fieldName.attr('placeholder', 'age');
           dataType.find('option').hide();
           dataType.find('option.number').show();
           dataType.val('int');
           maxLength.val('10');
           otherOption.html(defaultOtherOption);
        }
        
        //  spinners
        if( inputType === 'spinner') {
           fieldName.attr('placeholder', 'age');
           dataType.find('option').hide();
           dataType.find('option.number').show();
           dataType.val('int');
           maxLength.val('10');
           
           var stepper = '<div class="input-group"><input type="text" name="fields[' +fieldNameVal+ '][step]" class="other-option form-control spinner" placeholder="1" value="1"></div>';
           otherOption.html(stepper);
           otherOption.find('.spinner').btSpinner({
                step: 1,
                orientation: 'vertical',
                position: 'right'
            });
        }
        
        // data pickers
        if( inputType === 'radio' || inputType === 'checkbox' || inputType === 'dropdown' || inputType === 'multi-dropdown' || inputType === 'tagsinput') {
           fieldName.attr('placeholder', 'choose');
           dataType.find('option').show();
           dataType.val('varchar');
           maxLength.val('100');
        }
        
        // time picker
        if( inputType === 'time') {
           fieldName.attr('placeholder', 'time');
           dataType.find('option').hide();
           dataType.find('option.time').show();
           dataType.find('option.text').show();
           dataType.val('time');
           maxLength.val('10');
           
           var timeFormat = '<select name="fields[' +fieldNameVal+ '][format]" class="other-option form-control">\n\
                <option value="12">12 Hours</option>\n\
                <option value="24">24 Hours</option>\n\
            </select>\n';
            otherOption.html(timeFormat);
        }
        
        // date picker
        if( inputType === 'date' || inputType === 'date-range') {
           fieldName.attr('placeholder', 'date');
           dataType.find('option').hide();
           dataType.find('option.date').show();
           dataType.find('option.text').show();
           dataType.val('date');
           maxLength.val('50');
           otherOption.html(defaultOtherOption);
        }
        
        // date and time picker
        if( inputType === 'datetime' || inputType === 'datetime-range') {
           fieldName.attr('placeholder', 'datetime');
           dataType.find('option').hide();
           dataType.find('option.datetime').show();
           dataType.find('option.text').show();
           dataType.val('datetime');
           maxLength.val('100');
           otherOption.html(defaultOtherOption);
        }
        
        // timezone picker
        if( inputType === 'timezone') {
           fieldName.attr('placeholder', 'timezone');
           dataType.find('option').hide();
           dataType.find('option.text').show();
           dataType.val('varchar');
           maxLength.val('100');
           otherOption.html(defaultOtherOption);
        }
        
        // image uploads
        if( inputType === 'image-upload' ) {
           fieldName.attr('placeholder', 'upload');
           dataType.find('option').hide();
           dataType.find('option.text').show();
           dataType.val('text');
           maxLength.val('');
           
           var fileFormats = '<input type="text" name="fields[' +fieldNameVal+ '][file-formats]" class="other-option form-control tags-input" placeholder="Tags" value="jpg,gif,png">';
           otherOption.html(fileFormats);
           otherOption.find('.tags-input').tagsinput({});
        }
        
        // file uploads
        if( inputType === 'file-upload' || inputType === 'button-upload') {
           fieldName.attr('placeholder', 'upload');
           dataType.find('option').hide();
           dataType.find('option.text').show();
           dataType.val('text');
           maxLength.val('');
           
           var fileFormats = '<input type="text" name="fields[' +fieldNameVal+ '][file-formats]" class="other-option form-control tags-input" placeholder="Tags" value="txt,doc,docx">';
           otherOption.html(fileFormats);
           otherOption.find('.tags-input').tagsinput({});
        }
        
        // toggle
        if( inputType === 'toggle') {
           fieldName.attr('placeholder', 'toggle');
           dataType.find('option').hide();
           dataType.find('option.text').show();
           dataType.find('option.number').show();
           dataType.val('boolean');
           maxLength.val('10');
           
           var toggleText = '<input type="text" name="fields[' +fieldNameVal+ '][toggle-yes]" class="other-option form-control" placeholder="yes" value="yes">';
           toggleText += '<input type="text" name="fields[' +fieldNameVal+ '][toggle-yes]" class="other-option form-control" placeholder="no" value="no">';
           otherOption.html(toggleText);
        }
        
        // color
        if( inputType === 'color') {
           fieldName.attr('placeholder', 'color');
           dataType.find('option').hide();
           dataType.find('option.text').show();
           dataType.val('varchar');
           maxLength.val('25');
           
           var timeFormat = '<select name="fields[' +fieldNameVal+ '][format]" class="other-option form-control">\n\
                <option value="hex">Hex - #ffffff</option>\n\
                <option value="rgb">RGB - rgb(255,255,255)</option>\n\
                <option value="rgba">RGBA - rgba(255,255,255,0.50)</option>\n\
                <option value="hsl">HSL - hsl(255,57%,35%)</option>\n\
                <option value="hsla">HSLA - hsla(255,57%,35%,0.50)</option>\n\
            </select>\n';
            otherOption.html(timeFormat);
        }
        
        // masked
        if( inputType === 'masked') {
           fieldName.attr('placeholder', 'date');
           dataType.find('option').show();
           dataType.find('option.multi-dropdown').hide();
           dataType.val('varchar');
           maxLength.val('100');
           
           var regexText = '<input type="text" name="fields[' +fieldNameVal+ '][regex-format]" class="other-option form-control" placeholder="" value="">';
           otherOption.html(regexText);
        }
        
        // captcha
        if( inputType === 'captcha') {
           fieldName.attr('placeholder', 'captcha');
           dataType.find('option').hide();
           dataType.find('option.text').show();
           dataType.val('varchar');
           maxLength.val('25');
           
           var capthcaLength = '<div class="input-group"><input type="text" name="fields[' +fieldNameVal+ '][length]" class="other-option form-control spinner" placeholder="6" value="6"></div>';
           otherOption.html(capthcaLength);
           otherOption.find('.spinner').btSpinner({
                step: 1,
                orientation: 'vertical',
                position: 'right'
            });
        }
        
        // geolocation
        if( inputType === 'geolocation') {
           fieldName.attr('placeholder', 'geolocation');
           dataType.find('option').hide();
           dataType.find('option.text').show();
           dataType.val('varchar');
           maxLength.val('100');
           otherOption.html(defaultOtherOption);
        }
        
    });
    
}

$(function() {
    
//    alert( changeCase('BaAZinga ka eEHKL!', 'snake') );
//    alert( changeCase('big Bubble_Bath mokeyBar billy-jeans Bubble-Bubble Beatle_battle', 'humanUpper') );

//    var x = 'big Bubble_Bath mokeyBar billy-jeans Bubble-Bubble Beatle_battle';
//    alert( x.toCamel() );

    
    // validation rules
    var rules = {};
    rules['name']          = set_rules('name', 'name', 'required|maxlength[100]');
    rules['plural-name']   = set_rules('plural-name', 'plural name', 'required|not_equal[name]|maxlength[100]');
    rules['description']   = set_rules('description', 'description', 'maxlength[1000]');

    // add form validation
    addFormValidation( '#role-form', rules );
    
    initializeElements();
    addEventListeners();
});